package com.teach.demo01;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Arrays;

public class TCPServer {

	private static final int PORT = 1000;

	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		try {

			// 创建服务器并绑定IP和port
			// 写法一
//			serverSocket = new ServerSocket();
//			SocketAddress address = new InetSocketAddress(PORT);// 服务所有IP的端口
//			address = new InetSocketAddress(InetAddress.getByName("192.168.31.10"), PORT);
//			serverSocket.bind(address);

			// 写法二
			serverSocket = new ServerSocket(PORT);// 绑定服务所有IP的端口
//			serverSocket = new ServerSocket(PORT, 50, InetAddress.getByName("192.168.31.10"));
			// port: 端口
			// backlog : [直译：待办的事务],请求的传入连接队列的最大长度，默认：50
			// InetAddress ：网络地址，ip
			
			// 服务器创建完成
			System.out.println("服务器创建完成["+serverSocket.getInetAddress().getHostAddress()+":"+serverSocket.getLocalPort()+"]");

			
			// 接收一个客户端连接,阻塞的方法,必须要有客户端连接才会执行完成
			Socket client = serverSocket.accept();
			
			System.out.println(client.getPort());
			System.out.println(client.getInetAddress());
			System.out.println(client.getLocalPort());
			System.out.println(client.getLocalAddress());
			System.out.println(client.getRemoteSocketAddress());
			System.out.println(client.getInputStream());
			System.out.println(client.getOutputStream());
			
			
			//接受一段客户端发送的字节数组
			InputStream in = client.getInputStream();
			byte[] bs = new byte[10];
			int len = in.read(bs);
			System.out.println("接受一段客户端发送的字节数组:"+len+" = "+Arrays.toString(bs));
			
			//向客户端发送一段字节数组
			OutputStream out = client.getOutputStream();
			bs[9]=9;
			out.write(bs);
			out.flush();
			System.out.println("向客户端发送一段字节数组");
			
			System.out.format("关闭客户端[%s:%s]",client.getInetAddress().getHostAddress(),client.getPort());
			client.close();//关闭客户端
			serverSocket.close();//关闭服务器端
			

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
